﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
//using DHQGHN.DAL.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class HhRelationshipController : BaseController
    {
        HhRelationshipBO hhBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HhRelationshipController));

        public ActionResult Index(HhRelationshipModel hModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (hModel == null) hModel = new HhRelationshipModel();

                var model = search(hModel, pageIndex, currentId);
                return View("~/Views/HhRelationship/HhRelationship.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Hiển thị form thêm mới người dùng
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        [HttpPost]
        //[CustomAuthorize]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionPrepareCreateOrUpdateHh(int? hh_relationship_Id)
        {
            try
            {
                HhRelationshipModel hh = null;
                if (hh_relationship_Id != null && hh_relationship_Id > 0)
                {
                    hhBO = new HhRelationshipBO();
                    hh = new HhRelationshipModel(hhBO.GetHhById(hh_relationship_Id));
                    //u = unitOfWork.Users.GetById((int)userId);
                    //if (u != null)
                    //{
                    //    user = new UserModel(u);
                    //}
                }
                if (hh == null)
                {
                    hh = new HhRelationshipModel()
                    {
                        NAME = string.Empty,
                        CODE = string.Empty,
                        DESCRIPTIONS = string.Empty,
                        HH_RELATIONSHIP_ID = 0,
                        DELETED = 0
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/HhRelationship/_HhModel.cshtml", hh);
                }
                //RedirectToAction("ManageUsers", "Admin");
                return View(hh);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(HhRelationshipModel hModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                var model = search(hModel, pageIndex, currentId);
                return PartialView("~/Views/HhRelationship/_HhList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Thêm mới người dùng
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        //[ValidateJsonAntiForgeryToken]
        //[CustomAuthorize]
        [ValidateInput(false)]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionCreateOrUpdateHh(HhRelationshipModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    hhBO = new HhRelationshipBO();
                    bool result = hhBO.createOrUpdateHh_relationship(model.toDALModel());
                    if (result)
                    {
                        if (model.HH_RELATIONSHIP_ID != null && model.HH_RELATIONSHIP_ID > 0)
                        {
                            return Json(JsonResponse.Json200("Cập nhật thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        public ActionResult actionDelete(int hhId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    hhBO = new HhRelationshipBO();
                    bool result = hhBO.deleteHh_relationship(hhId);
                    if (result)
                    {
                        return Json(JsonResponse.Json200("Xóa thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        public JsonResult CheckExistHhName(string Name, int? id)
        {
            try
            {
                var isExist = false;

                if (!string.IsNullOrEmpty(Name))
                {
                    HhRelationshipModel appModel = new HhRelationshipModel()
                    {
                        NAME = Name

                    };
                    var model = search(appModel, 0, -1);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (HhRelationshipModel app in lstItem)
                        {
                            if (id != null && id > 0)
                            {
                                //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                                if (app.HH_RELATIONSHIP_ID != id)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.HhNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ma ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="id"> </param>
        /// <returns></returns>
        //[CustomAuthorize]
        //[ValidateJsonAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public JsonResult CheckExistHhCode(string Code, int? id)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(Code))
                {
                    HhRelationshipModel appModel = new HhRelationshipModel()
                    {
                        CODE = Code
                    };
                    var model = search(appModel, 0, -1);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (HhRelationshipModel app in lstItem)
                        {
                            if (id != null && id > 0)
                            {
                                //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                                if (app.HH_RELATIONSHIP_ID != id)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.HhCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        private DataPage<HhRelationshipModel> search(HhRelationshipModel hModel, int pageIndex, int currentId)
        {
            try
            {
                hhBO = new HhRelationshipBO();
                //Binding ListItem
                //BindDataToCcbPeopleType();

                //var model = peopleBo.GetListPaging(pModel, PageSize, page);
                var DALModel = hhBO.GetDynamicListPaging(hModel.toDALModel(), PageSize, pageIndex);
                var model = new DataPage<HhRelationshipModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.HhRelationshipModel hh in lstItem)
                {
                    model.Data.Add(new HhRelationshipModel(hh));
                }

                HhRelationshipModel hhModel = null;
                if (currentId >= 0 && model.Data.Count > 0)
                {
                    hhModel = model.Data.Find(user => user.HH_RELATIONSHIP_ID == currentId);
                    model.CustomData = hhModel;
                }
                else
                {
                    model.CustomData = hModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "HhRelationship",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "hh-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch
            {
                throw;
            }
        }
    }
}